package org.yinxianren.java.test.thread;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 在面向对象编程的世界中，工厂模式是最有用的设计模式。它是一个创造模式，还有它的目的是创建一个或几个类的对象的对象。
 * 然后，当我们想创建这些类的对象时，我们使用工厂来代替new操作。
 * 有了这个工厂，我们有这些优势来集中创建对象们：
 * 更简单的改变了类的对象创建或者说创建这些对象的方式。
 * 更简单的为了限制的资源限制了对象的创建。 例如， 我们只new一个此类型的对象。
 * 更简单的生成创建对象的统计数据。
 * Java提供一个接口， ThreadFactory 接口实现一个线程对象工厂。 并发 API 使用线程工厂来创建线程的一些基本优势。
 */
public class MyThreadFactory implements ThreadFactory {
//counter，整数，用来储存线程对象的数量；
// name，字符串，每个创建线程的名字；
// stats, 字符串list, 储存创建的线程对象的统计数据
    private int counter;
    private String name;
    private List<String> stats;
    public MyThreadFactory(String name){
        counter=0;
        this.name=name;
        stats=new ArrayList<String>();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t=new Thread(r,name+"-Thread_"+counter);
        counter++;
        stats.add(String.format("created thread %d with name %s on %s\n",t.getId(),t.getName(),new Date()));
        return t;
    }

    public String getStats(){
        StringBuffer buffer=new StringBuffer();
        Iterator<String> it=stats.iterator();
        while (it.hasNext()) {
            buffer.append(it.next());
            buffer.append("\n");
        }
        return buffer.toString();
    }


}
class Task2 implements Runnable {
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class MianTen{
    public static void main(String[] args) {
        MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
        Task2 task=new Task2();

        Thread thread;
        System.out.printf("Starting the Threads\n");
        for (int i=0; i<10; i++){
            thread=factory.newThread(task);
            thread.start();
        }

        System.out.printf("Factory stats:\n");
        System.out.printf("%s\n",factory.getStats());
/*
Starting the Threads
Factory stats:
created thread 12 with name MyThreadFactory-Thread_0 on Sun May 12 23:16:54 CST 2019
created thread 13 with name MyThreadFactory-Thread_1 on Sun May 12 23:16:54 CST 2019
created thread 14 with name MyThreadFactory-Thread_2 on Sun May 12 23:16:54 CST 2019
created thread 15 with name MyThreadFactory-Thread_3 on Sun May 12 23:16:54 CST 2019
created thread 16 with name MyThreadFactory-Thread_4 on Sun May 12 23:16:54 CST 2019
created thread 17 with name MyThreadFactory-Thread_5 on Sun May 12 23:16:54 CST 2019
created thread 18 with name MyThreadFactory-Thread_6 on Sun May 12 23:16:54 CST 2019
created thread 19 with name MyThreadFactory-Thread_7 on Sun May 12 23:16:54 CST 2019
created thread 20 with name MyThreadFactory-Thread_8 on Sun May 12 23:16:54 CST 2019
created thread 21 with name MyThreadFactory-Thread_9 on Sun May 12 23:16:54 CST 2019
 */
    }
}